<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/6/20
 * Time: 14:07
 * 盘点流程：1、获取盘点计划  2、输入盘点数据  3、提交数据  4、后台最终审核，写入盘点库存
 */

namespace iBrand\Shop\Server\Controllers\V2;


use iBrand\Component\Goods\Models\Goods;
use iBrand\Component\Goods\Models\GoodsProduct;
use iBrand\Component\Goods\Repositories\GoodsProductRepository;
use iBrand\Component\Purchase\Repositories\StockRecordRepository;
use iBrand\Component\Purchase\Repositories\TakeStockRepository;
use iBrand\Shop\Core\Models\TakeStockPlan;
use iBrand\Shop\Core\Models\TakeStockPlanItems;
use iBrand\Shop\Core\Repositories\O2oGoodsProductsRepository;
use iBrand\Shop\Core\Repositories\O2oGoodsRepository;
use iBrand\Shop\Core\Service\WarehouseService;
use iBrand\Shop\Server\Service\WarehouseProductService;
use Illuminate\Support\Facades\DB;

class StockTakeController extends \iBrand\Common\Controllers\Controller
{

    protected $warehouseProductService;
    protected $takeStockRepository;
    protected $goodsProductRepository;
    protected $warehouseService;
    protected $o2oGoodsRepository;
    protected $o2oGoodsProductsRepository;
    protected $stockRecordRepository;

    public function __construct(WarehouseProductService $warehouseProductService,
                                TakeStockRepository $takeStockRepository,
                                GoodsProductRepository $goodsProductRepository,
                                WarehouseService $warehouseService,
                                O2oGoodsRepository $o2oGoodsRepository,
                                O2oGoodsProductsRepository $o2oGoodsProductsRepository,
                                StockRecordRepository $stockRecordRepository)
    {
        $this->warehouseProductService = $warehouseProductService;
        $this->takeStockRepository = $takeStockRepository;
        $this->goodsProductRepository = $goodsProductRepository;
        $this->warehouseService = $warehouseService;
        $this->o2oGoodsRepository = $o2oGoodsRepository;
        $this->o2oGoodsProductsRepository = $o2oGoodsProductsRepository;
        $this->stockRecordRepository = $stockRecordRepository;
    }

    /**
     * 获取盘点计划列表
     * @return \Illuminate\Http\Response
     */
    public function getTakePlans()
    {
        $plans = TakeStockPlan::where('status', 0)->get();
        return $this->success(['plans' => $plans]);
    }

    /**
     * 根据SKU获取盘点商品数据
     */
    public function getTakeProductData()
    {
        $sku = request('sku');
        $plan_id = request('plan_id');
        $clerk = auth('clerk')->user();
        $shop_id = $clerk->shop_id;

        $product = $this->warehouseProductService->getProductDataBySku($sku);

        if (!$product) {
            return $this->failed('商品不存在');
        }

        if (!$item = TakeStockPlanItems::where('take_stock_plan_id', $plan_id)
            ->where('base_product_id', $product->id)
//            ->where('status', 0)
            ->first()) {
            return $this->failed('该商品不在本次盘点计划之内');
        }

        $currentStock = $this->stockRecordRepository->getCurrentStock($shop_id, $product->id, GoodsProduct::class);
        $product->currentStock = $currentStock;

        return $this->success($product);

    }

    /**
     * 根据商品编号获取盘点商品数据
     * @return \Illuminate\Http\Response|mixed
     */
    public function getTakeProductDataByCode()
    {
        $sku = request('sku');
        $plan_id = request('plan_id');
        $clerk = auth('clerk')->user();
        $shop_id = $clerk->shop_id;

        $products = $this->warehouseProductService->getProductDataByCode($sku);

        if (!$products->count()) {
            return $this->failed('商品不存在');
        }

        $products = $products->filter(function ($item) use ($plan_id) {
            return $item = TakeStockPlanItems::where('take_stock_plan_id', $plan_id)
                ->where('base_product_id', $item->id)
                ->first();
        })->all();
        $products = array_values($products);
        foreach ($products as $product) {
            $currentStock = $this->stockRecordRepository->getCurrentStock($shop_id, $product->id, GoodsProduct::class);
            $product->currentStock = $currentStock;
        }
        \Log::info($products);
        return $this->success($products);
    }

    /**
     * 盘点动作
     * @return mixed
     */
    public function saveTakeStock()
    {
        $clerk = auth('clerk')->user();
        $plan_id = request('plan_id');
        $shop_id = $clerk->shop_id;
        $goods = request('goods');

        $goodsCollect = collect($goods);

        try {
            DB::beginTransaction();
            $stockData = [
                'shop_id' => $shop_id,
                'code' => 'TS' . date('YmdHis') . mt_rand(10000000, 99999999),
                'clerk_id' => $clerk ? $clerk->id : 0,
                'total' => $goodsCollect->sum('quantity'),
                'difference_count' => 0,
                'difference_amount' => 0,
                'remark' => request('remark'),
                'plan_id' => $plan_id
            ];

            $takeStock = $this->takeStockRepository->create($stockData);

            foreach ($goods as $good) {
                $factory_price = isset($good['price']) ? $good['price'] : 0;
                if ($good['currentSku']) {
                    $product = $this->goodsProductRepository->getProductBySku($good['currentSku']);
                    $item_id = $product->id;
                    $item_type = GoodsProduct::class;

                    if (!$factory_price) {
                        $factory_price = $product->goods->factory_price;
                        $good['price'] = $factory_price;
                    }

                } else {
                    $item_id = $good['goods_id'];
                    $item_type = Goods::class;
                }

                if (!$takeStockPlanItems = TakeStockPlanItems::where('take_stock_plan_id', $plan_id)->where('base_product_id', $item_id)->first()) {
                    return $this->failed($good['goods_no'] . ' 不在本次盘点计划内');
                }

//                if ($takeStockPlanItems->status == 1) continue;


                $this->warehouseService->addTakeStockItem($takeStock->id, $good, $item_id, $item_type, 0);

                /*$this->warehouseService->addTakeStockRecord($shop_id, $takeStock->id, $good, $item_id, $item_type);

                $o2oGoods = $this->o2oGoodsRepository->findWhere(['status' => 1, 'goods_id' => $good['goods_id'], 'shop_id' => $shop_id])->first();
                $o2oGoods->restoreStock($good['quantity']);

                $this->addO2oGoodsProduct($shop_id, $o2oGoods->id, $good, $item_id);

                $takeStockPlanItems->status = 1;
                $takeStockPlanItems->save();*/
            }

            $difference_count = $takeStock->items()->sum('difference_count');
            $difference_amount = $takeStock->items()->sum('difference_amount');
            $takeStock->difference_count = $difference_count;
            $takeStock->difference_amount = $difference_amount;
            $takeStock->save();


            DB::commit();

            return $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::info($exception->getTraceAsString());
            \Log::info($exception->getMessage());
            return $this->failed($exception->getMessage());
        }
    }

    private function addO2oGoodsProduct($shop_id, $o2oGoodsId, $good, $product_id)
    {
        $o2oGoodsProduct = $this->o2oGoodsProductsRepository->findWhere(['shop_id' => $shop_id, 'o2o_goods_id' => $o2oGoodsId, 'goods_id' => $good['goods_id'], 'product_id' => $product_id])->first();
        if ($o2oGoodsProduct) {
            $o2oGoodsProduct->store_nums = $good['quantity'];
            $o2oGoodsProduct->save();
        }
    }

}